﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.IO;
using LogLib;
using ComLib.ComFun;
using System.Reflection;

namespace ComLib.ConfigService
{
    public abstract class XmlSerializeBase : IConfig
    {
        [XmlIgnore]
        public virtual string ConfigDirectory
        {
            get
            {
                string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
                directory = directory.Substring(6);
                return directory;
            }
        }

        [XmlIgnore]
        protected string _error = "";

        [XmlIgnore]
        protected string _strConfigPath = "";

        [XmlIgnore]
        protected int _nVer = 0;

        [XmlIgnore]
        public string ErrorMessage
        {
            protected set
            {
                _error = value;
                LoadingError.AddErrorMessage(value);
            }
            get
            {
                return _error;
            }
        }

        [XmlIgnore]
        public virtual string ConfigFilePath
        {
            get 
            {
                if (string.IsNullOrEmpty(_strConfigPath))
                {
                    string className = this.GetType().Name;
                    _strConfigPath = Path.Combine(ConfigDirectory, "config", className + ".xml");
                }
                return _strConfigPath;
            }
        }

        public int nVer
        {
            get { return _nVer; }
            set { _nVer = value; }
        }

        public XmlSerializeBase()
        {

        }

        public abstract bool Serialize();
      
        public abstract bool Load();
 
        public bool Save()
        {
            _error = "";
            if (!Serialize())
            {
                ErrorMessage = Serializer.Message;
                return false;
            }
            return true;
        }
    }
}
